<template>
  <div class="documentDetails">
    <div class="header">
      <mt-header
        fixed
        :title="titleName"
      >
        <!-- <router-link
          to=""
          slot="left"
        >
          <mt-button
            icon="back"
            @click="$router.back(-1)"
            class="leftButton"
          ></mt-button>
        </router-link>-->
      </mt-header>
    </div>
    <div class="mian pad-l-r-30">
      <!-- 单据 详情 -->
      <mt-navbar v-model="selected">
        <mt-tab-item id="1">单据详情</mt-tab-item>
        <mt-tab-item id="2">流程图</mt-tab-item>
      </mt-navbar>
      <mt-tab-container v-model="selected">
        <mt-tab-container-item id="1">
          <div class="templetData">
            <div class="templetHeader templetBox">
              <div
                class="item"
                v-for="(item,index) in templetHeader"
                :key="index"
              >
                <p class="title">{{item.colname}}</p>
                <p>{{item.colvalue}}</p>
              </div>
            </div>
            <div
              class="templetBody"
              v-for="(item,index) in templetBody"
              :key="index"
            >
              <div class="title">{{item.tabTitle}}</div>
              <div
                class="templetBox"
                v-for="(ite,indx) in item.tabdata"
                :key="indx"
              >
                <div
                  v-for="(it,idx) in ite"
                  :key="idx"
                >
                  <div class="item">
                    <p class="title">{{it.colname}}</p>
                    <p>{{it.colvalue}}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <SmallTitlePanel
            title="审批历史"
            class="auditingHistoryBox"
          >
            <ul class="auditingHistory pad-l-r-20">
              <li
                class="item"
                v-for="(item,index) in 0"
                :key="index"
              >
                <div class="dealMan">
                  <span>{{item.dealMan}}</span>
                  <span
                    v-if="item.approveresult === 'Q'"
                    style="color:red;"
                  >审批中</span>
                  <span
                    v-else-if="item.approveresult === 'Y'"
                    style="color:green;"
                  >审批完成</span>
                  <span
                    v-else
                    style="color:#aaa;"
                  >提交</span>
                </div>
                <p class>处理人:{{item.checkman?item.checkman:''}}</p>
                <p
                  class="checkNote pad-t-10"
                  v-show="item.checknote"
                >批语:"{{item.checknote?item.checknote:''}}"</p>
                <div class="dealDate pad-t-10">{{item.dealdate?item.dealdate:''}}</div>
              </li>
              <el-steps
                direction="vertical"
                finish-status="success"
                :active="msgVOList.length - 1"
              >
                <el-step
                  v-for="(item,index) in msgVOList"
                  :key="index"
                >
                  <template slot="description">
                    <li class="item">
                      <div class="dealMan">
                        <span>{{item.checkman}}</span>
                        <span class="date">{{item.dealdate}}</span>
                      </div>
                      <p>
                        <span
                          v-if="item.approveresult === 'Q'"
                          style="color:red;"
                        >审批中</span>
                        <span
                          v-else-if="item.approveresult === 'Y'"
                          style="color:green;"
                        >审批完成</span>
                        <span
                          v-else
                          style="color:#000;"
                        >提交申请</span>
                      </p>
                      <p
                        class="checkNote pad-t-10"
                        v-show="item.checknote"
                      >批语:"{{item.checknote?item.checknote:''}}"</p>
                    </li>
                  </template>
                </el-step>
              </el-steps>
            </ul>
          </SmallTitlePanel>
          <!-- 审批历史信息 -->
          <SmallTitlePanel
            title="审批意见"
            v-if="isShowApprovalOpinion"
          >
            <div class="htmlCode pad-l-r-20 yijian">
              <mt-field
                placeholder="请输入审批批语"
                type="textarea"
                class="opinion pad-l-r-10"
                rows="4"
                :attr="{ maxlength: 50 }"
                v-model="approval.opinion"
              ></mt-field>
            </div>
          </SmallTitlePanel>
        </mt-tab-container-item>
        <mt-tab-container-item id="2">
          <div
            class="flowChart"
            v-if="flowChart"
          >
            <img :src="`data:image/jpeg;base64,${flowChart}`">
          </div>
        </mt-tab-container-item>
      </mt-tab-container>
    </div>
    <div
      class="footer"
      v-if="isShowApprovalOpinion"
    >
      <div class="seizASeat"></div>
      <mt-tabbar
        class="actionButtons"
        v-model="selectesd"
        fixed
      >
        <mt-tab-item
          id="agree"
          v-if="canApprove"
        >
          <div @click="submission('agree')">批准</div>
        </mt-tab-item>
        <mt-tab-item
          id="disagree"
          v-if="canReject"
        >
          <div @click="submission('disagree')">驳回</div>
        </mt-tab-item>
        <!-- <mt-tab-item
          id="disagree"
          v-if="billType==='auditingWait'"
        >
          <div @click="approveBtnClick('disagree')">拒绝</div>
        </mt-tab-item>-->
        <!-- <mt-tab-item
          id="reject"
          v-if="reject && billType==='auditingWaitsssss'"
        >
          <div @click="approveBtnClick('reject')">驳回</div>
        </mt-tab-item>-->
        <!-- <mt-tab-item
          id="unapprove"
          v-if="billType==='auditingComplete'"
        >
          <div @click="approveBtnClick('unapprove')">取消审批</div>
        </mt-tab-item>-->
      </mt-tabbar>
    </div>
    <!-- 审批意见 -->
    <mt-popup
      v-model="popupVisible"
      :closeOnClickModal="true"
      :modal="true"
      position="right"
      class="popupVisible"
    >
      <div class="header">
        <mt-header
          fixed
          title="增加审批意见"
        >
          <router-link
            to
            slot="left"
          >
            <mt-button
              icon="back"
              @click="popupVisible = false"
              class="leftButton"
            ></mt-button>
          </router-link>
        </mt-header>
      </div>
      <div class="content pad-t-20">
        <div class="flow">
          <!-- <el-steps
            direction="vertical"
            :active="1"
          >
            <el-step
              title="步骤 1"
              @click.native="onClick(21)"
              v-for=" in flow"
              :key="index"
            ></el-step>
          </el-steps>-->
          <el-select
            v-model="approval.flowValue"
            placeholder="请选择驳回环节"
            v-show="selectesd === 'reject'"
            class="flowValue"
          >
            <el-option
              v-for="(item,index) in flow"
              :key="index"
              :label="`${item.xh}.${item.name}`"
              :value="item.id"
              :disabled="item.disabled !== 'Y'"
            ></el-option>
          </el-select>
        </div>
        <div class="opinionBox">
          <mt-field
            placeholder="请输入审批批语"
            type="textarea"
            class="opinion pad-l-r-10"
            rows="4"
            :attr="{ maxlength: 50 }"
            v-model="approval.opinion"
          ></mt-field>
        </div>
        <div class="popupSeizASeat"></div>
        <div class="bottomBox pad-l-r-20">
          <mt-button
            class="submission"
            type="primary"
            @click.native="submission"
          >提交</mt-button>
        </div>
      </div>
    </mt-popup>
  </div>
</template>


<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import { Message, Loading } from 'element-ui';
import { Indicator, Toast } from 'mint-ui';

import { getMsgId, verifyUser } from '@/utils/index';
// import { debounce } from '@/decorator';

import { findIndex, debounce } from 'lodash';
import Qs from 'qs';
// import { approvalType } from '@/typeDefinition';

import SmallTitlePanel from '@/components/SmallTitlePanel/SmallTitlePanel.vue';

const components = {
  SmallTitlePanel,
};
@Component({
  components,
})
export default class documentDetails extends Vue {
  selected: string = '1';

  htmlCode: any = {};

  selectesd: string = '';

  agree: boolean = false;

  disagree: boolean = false;

  reject: boolean = false;

  canApprove: boolean = false;

  canReject: boolean = false;

  unApprove: boolean = false;

  popupVisible: boolean = false;

  approval: any = {
    opinion: '',
    flowValue: '',
  };

  detailsData: any = {};

  msgVOList: any = [];

  flow: any = [];

  loading: any;

  detailNum: string = '';

  // 工作流图片
  flowChart: string = '';

  titleName: string = '表头';

  get templetHeader() {
    if (!this.htmlCode.head) return [];
    if (!this.htmlCode.head[0]) return [];
    if (!this.htmlCode.head[0].tabdata) return [];
    return this.htmlCode.head[0].tabdata[0];
  }

  get templetBody() {
    console.log('this.htmlCode.body :', this.htmlCode.body);
    return this.htmlCode.body || [];
  }

  get userId() {
    return this.$store.getters.userId || verifyUser();
  }

  get isShowApprovalOpinion() {
    return this.canApprove || this.canReject;
  }

  get groupId() {
    return this.$store.getters.groupId;
  }

  get msgId() {
    // return this.$store.state.document.msgId;
    return getMsgId();
  }

  get documentDetail() {
    return this.$store.state.document.documentDetail;
  }

  get billType() {
    return this.$store.state.document.billType;
  }

  // 获取单据流程图
  getTaskFlowChart(detail: string, workflowType: string) {
    this.$api
      .getTaskFlowChart(this.userId, detail, workflowType)
      .then((res) => {
        this.flowChart = res.data.pic;
      })
      .catch(() => { });
  }

  submission(type: string) {
    // 审批  提交 事件
    const action = type;
    const opinion = this.approval.opinion.toString();
    const flowValue = this.approval.flowValue;
    if (action === 'reject' && (flowValue === '' || flowValue === null)) {
      this.openMessage('请选择驳回环节', 'warning', false);
      return;
    }
    this.approve(action, opinion, flowValue);
  }

  unApproveFun() {
    this.openLoading();
    this.$api
      .getUnApprove(this.groupId, this.userId, this.detailNum)
      .then((res: any) => {
        this.loading.close();
        this.openMessage('取消审批完成', 'success');
      })
      .catch((err: any) => {
        this.loading.close();
      });
  }

  approveBtnClick(sign: string) {
    // 审批 按钮点击 选择 事件
    this.popupVisible = true;
  }

  openLoading() {
    this.loading = Loading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.2)',
    });
  }

  approveReject(nodeId: string, node: string) {
    // 审批 - 驳回 fun
    this.openLoading();
    this.$api
      .getdoReject(this.groupId, this.userId, this.documentDetail, nodeId, node)
      .then((res) => {
        this.loading.close();
        this.openMessage('驳回成功', 'success');
      })
      .catch((err) => {
        this.loading.close();
        this.openMessage(err.error_msg);
      });
  }

  approve(sign: string, opinion: string, flowValue: string) {
    // 调取审批接口
    this.openLoading();
    this.$api
      .doAction(this.userId, this.detailsData.detail, opinion, sign, flowValue)
      .then((res) => {
        this.loading.close();
        this.openMessage('审批成功', 'success');
        this.getMessageDetail(this.msgId);
      })
      .catch((err) => {
        this.loading.close();
        this.openMessage(err.message);
      });
  }

  approvalDetails(detail: string) {
    // 调取单据审批详情
    this.$api
      .approvalDetails(this.groupId, this.userId, detail)
      .then((res: any) => {
        this.msgVOList = res.msgVOList;
        this.flow = res.xmlList;
        this.loading.close();
      })
      .catch((err: any) => {
        this.loading.close();
        // this.openMessage('请求失败，返回首页');
      });
    // });
  }

  chineseChangeBinarySystem(val: string) {
    // 汉字转二进制
    val = encodeURI(val);
    return val;
  }

  // 调取单据详情
  getMessageDetail(msgId: string) {
    this.openLoading();
    // return new Promise((resolve) => {
    this.$api
      .getTempletData(this.userId, msgId)
      .then((res: any) => {
        const detData = res.data;
        const detail = detData.detail;
        const workflowType = detData.workflow_type;
        this.titleName = detData.name;
        console.log('detData ++++++++++++++++++++:', detData.content.data);
        this.htmlCode = detData.content.data;
        this.agree = detData.agree === 'true';
        this.disagree = detData.disAgree === 'true';
        this.detailNum = detail;
        this.canApprove = detData.canApprove;
        this.canReject = detData.canReject;
        this.detailsData = detData;
        this.$store.dispatch('setDocumentDetail', detail);
        this.approveHistoryList(detail);
        this.getTaskFlowChart(detail, workflowType);
        this.loading.close();
      })
      .catch((err: any) => {
        this.loading.close();
        this.openMessage('请求失败，返回首页');
      });
    // });
  }

  // 获取历史信息
  approveHistoryList(detail: string) {
    this.$api
      .approveHistoryList(this.userId, detail)
      .then((res: any) => {
        console.log('res :', res);
        this.msgVOList = res.data;
        // this.flow = res.xmlList;
        // this.reject = res.xmlList.some((item: any) => item.disabled === 'Y');
        // this.unApprove = res.unApprove === 'Y';
        // const unApprove = res.unApprove === 'Y';
        // console.log('unApprove :', unApprove);
      })
      .catch((err: any) => {
        // this.openMessage('请求失败，返回首页');
      });
  }

  getApprovalScheduleData(detail: string) {
    // 调取 单据详情
    this.openLoading();
    // return new Promise((resolve) => {
    this.$api
      .getNC63TaskList(this.groupId, this.userId, detail)
      .then((res) => {
        console.log('res  请求详情成功:', res);
        this.htmlCode = res.content.data;
        this.agree = res.agree;
        this.disagree = res.disAgree;
        this.loading.close();
      })
      .catch((err) => {
        this.loading.close();
        this.openMessage('请求失败，返回首页', 'error', false);
      });
    // });
  }

  openMessage(mess: string, type: any = 'error', goHome: boolean = true) {
    // 打开提示框 并且2s后返回首页
    Message({
      message: mess,
      type,
      duration: 2 * 1000,
      onClose: () => {
        // if (goHome) {
        //   this.$router.push('/');
        //   this.$store.dispatch('setBillType', 'auditingWait');
        // }
      },
    });
  }

  // async created() {
  //   await this.$store.dispatch('LoginByUsername', this.userId);
  // }
  created() {
    const msgId = this.msgId;
    console.log('msgId :', msgId);
    this.$store.dispatch('removeDocumentDetail');
    if (msgId) {
      // getMessageDetail;
      this.getMessageDetail(msgId);
    } else {
      this.openMessage('未取到值单据号');
    }
    // this.popupVisible = true;
    // this.selectesd = 'reject';

    console.log('billType :', this.billType);
    console.log('this.$store.state.document.billType :', this.$store);
  }

  mounted() {
    // const msgId = this.msgId;
    // console.log('msgId :', msgId);
    // this.$store.dispatch('removeDocumentDetail');
    // if (msgId) {
    //   // getMessageDetail;
    //   this.getMessageDetail(msgId);
    // } else {
    //   this.openMessage('未取到值单据号');
    // }
    // // this.popupVisible = true;
    // // this.selectesd = 'reject';

    // console.log('billType :', this.billType);
    // console.log('this.$store.state.document.billType :', this.$store);
  }
}
</script>

<style lang="scss" scoped>
.documentDetails {
  .templetData {
    .templetBox {
      margin: 0.1rem 0;
      border: 1px solid #ddd;
      border-bottom: 0;
      .item {
        display: flex;
        min-height: 35px;
        border-bottom: 1px solid #ddd;
        p {
          display: flex;
          padding: 0.08rem;
          align-items: center;
          // font-size: 0.12rem;
          flex: 3;
        }
        .title {
          border-right: 1px solid #ddd;
          display: flex;
          align-items: center;
          background: rgba(237, 245, 255, 0.6);
          flex: 1;
        }
      }
    }
    .templetHeader {
      margin-top: 0.2rem;
    }
    .templetBody {
      .title {
        padding: 0.1rem 0 0.1rem 0.2rem;
        background-color: #f1f1f1;
      }
    }
  }
  .seizASeat {
    height: 0.8rem;
  }
  .header {
    height: 40px;
  }
  .mian {
    .htmlCode {
      width: 100%;
      overflow-x: scroll;
    }
    .auditingHistoryBox {
      margin-top: 0.2rem;
      .auditingHistory {
        .item {
          border-bottom: 1px solid #ddd;
          padding: 0.1rem 0;
          font-size: 0.24rem;
          .dealMan {
            display: flex;
            justify-content: space-between;
          }
          .checkNote {
            word-wrap: break-word;
            word-break: break-all;
            overflow: hidden;
          }
          .dealDate {
            font-size: 0.2rem;
            color: #999;
          }
        }
      }
    }
  }
  .footer {
    .actionButtons {
      border-top: 1px solid #ddd;
      height: 0.8rem;
      .mint-tab-item {
        padding: 0;
        color: #26a2ff;
        background-color: #ffffff;
        &.is-selected {
          background-color: #ffffff;
        }
      }
    }
  }
  .popupVisible {
    overflow-y: auto;
    width: 6rem;
    height: 8rem;
    right: 10%;
    background-color: #fff;
    border: 1px solid #ddd;
    .content {
      .flowValue {
        width: 5.54rem;
        margin: 0 0.2rem;
      }
      .opinionBox {
        margin: 0.2rem;
        border: 1px solid #ddd;
        border-radius: 4px;
        overflow: hidden;
        // border-bottom: 20px solid #eee;
        .opinion {
          color: #26a2ff;
          font-size: 0.28rem;
          .mint-cell-value {
            background: red;
          }
          &.mint-cell:last-child {
            background: #fff;
          }
        }
      }
      .popupSeizASeat {
        height: 1.1rem;
      }
      .bottomBox {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 0.15rem 0.2rem;
        .submission {
          width: 100%;
          height: 0.8rem;
          font-size: 0.3rem;
        }
      }
    }
  }
  .flowChart {
    width: 100%;
    overflow: auto;
    img {
      // width: 100%;
    }
  }
}
</style>
<style lang="scss">
.documentDetails {
  .el-step__description {
    padding-right: 0;
    .date {
      color: #999;
    }
    &.is-success {
      color: #333;
    }
  }
  .divtext {
    border-bottom: 1px solid #ddd;
    height: 0.8rem;
    display: flex;
    align-items: center;
    .labeltext {
      width: 2.5rem;
      text-align: right;
      margin: 0 0.2rem 0 0;
      color: #999;
    }
  }
  .mint-tab-item {
    .mint-tab-item-label {
      height: 100%;

      border-left: 1px solid #ddd;
      border-right: 1px solid #ddd;
      div {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 0.24rem;
      }
    }
    &:last-child {
      .mint-tab-item-label {
        border-right: 0;
      }
    }
    &:first-child {
      .mint-tab-item-label {
        border-left: 0;
      }
    }
  }
  .htmlCode {
    table {
      width: 100%;
      td {
        background: #09c;
      }
    }
  }
  .popupVisible {
    .mint-cell-wrapper {
      background: #fff;
      background-image: none;
      border: 1px solid #ddd;
      .mint-cell-value {
        .mint-field-core {
          font-size: 0.28rem;
        }
      }
    }
  }
  .yijian {
    .mint-cell {
      border: 1px solid #ddd;
      .mint-cell-wrapper {
        background: #fff;
        background-image: none;
        .mint-cell-value {
          .mint-field-core {
            font-size: 0.28rem;
          }
        }
      }
    }
  }
}
</style>
